package actions.xml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.sql.SQLException;
import java.util.LinkedList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import persistencia.JAXBAgent;

import com.google.appengine.api.datastore.Blob;
import com.opensymphony.xwork2.ActionSupport;

import dominio.Categoria;
import dominio.xml.productsByCategories.XMLCategories;
import dominio.xml.productsByCategories.XMLList;


/* Esta accion crea el xml con la lista de las categorias */

public class createCategories extends ActionSupport{
	
	private static final long serialVersionUID = 1L;
	private XMLList xmlList = new XMLList();
	private Long owner_id;
	ByteArrayInputStream fileStream;
	private String fileContentType;
	private String fileName;
	
	public String execute() throws SQLException{
		
		/* Cogemos las categorias de la base de datos */
		LinkedList<Categoria> categorias = null;
		categorias = Categoria.readByUserId(owner_id, false);
		
		XMLCategories categoria;
		
		for(int i=0; i<categorias.size(); i++){
			
			/* Creamos el objeto XMLCategorie */
			categoria = new XMLCategories(categorias.get(i).getId(), categorias.get(i).getName());
		
			xmlList.addCategorie(categoria);
		}
		
		/* jc;
		try {
			jc = JAXBContext.newInstance(XMLList.class);
			Marshaller marshaller = jc.createMarshaller();
			marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "utf-8");
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal((XMLList)xmlList, System.out);
			
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.toString());
		}*/
		
		
		ByteArrayOutputStream productInfoArray;
		try {
			productInfoArray = JAXBAgent.marshal(XMLList.class,xmlList);
			Blob productInfoBlob= new Blob(productInfoArray.toByteArray());
			fileStream = new ByteArrayInputStream(productInfoBlob.getBytes());
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		fileContentType = "application/xml";
		fileName = "AllProducts.xml";
		
		
		return SUCCESS;
		
		
	}
	
	public Long getOwner_id() {
		return owner_id;
	}
	public void setOwner_id(Long owner_id) {
		this.owner_id = owner_id;
	}

	public ByteArrayInputStream getFileStream() {
		return fileStream;
	}

	public void setFileStream(ByteArrayInputStream fileStream) {
		this.fileStream = fileStream;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	
	
	
	

}
